import { timeoutTask, getRandom, showWxToast, showWxLoading, hideWxLoading } from '../../utils/index';
import { getGameState, sendBroadCast, getHbList, buyHb, hbqRecharge, getHbRankList } from '../../api/kbx/kbx';
import { wxPay } from '../../api/pay';
import defaultContent from '../../assets/constant/default';

const app = getApp();

// 礼物数组
const giftList = [
    {
        id: 1,
        gift: 'rocket1',
        name: '小号火箭',
        imgUrl: 'https://static.hudongmiao.com/joymewMp/zyz/rocket1.png',
    }, {
        id: 2,
        gift: 'rocket2',
        name: '中号火箭',
        imgUrl: 'https://static.hudongmiao.com/joymewMp/zyz/rocket2.png',
    }, {
        id: 3,
        gift: 'rocket3',
        name: '大号火箭',
        imgUrl: 'https://static.hudongmiao.com/joymewMp/zyz/rocket3.png',
    }
];
const wishList = [
    '醉酒饱德，不胜感激',
    '美酒佳肴,不甚荣幸',
    '感谢招待,祝愿安康',
    '小小红包,感谢招待'
];
let requestLock = false;
// 限制只有一个轮询存在
let tmpInterval = null; // 刚进入红包墙的轮询
let tmpInterval2 = null; // 点击开始游戏中的轮询
let baseMoney = 0;
Page({
    data: {
        gameStatus: 1, // 游戏状态(控制页面显示)
        myHbsVisible: false,
        isLuckyShow: false,
        luckyAni: '',
        hbs: [],
        chooseHbIds: [],
        remain: 3,
        activeGiftIndex: -1,
        gift_show: { //当前显示的礼物
            id: 3,
            gift: 'rocket3',
            name: '大号火箭',
            imgUrl: 'https://static.hudongmiao.com/joymewMp/zyz/rocket3.png',
            price: 0,
        },
        userId: '',
        openId: '',
        name: '',
        headImg: '',
        luckyHbs: [],
        sort: '',
        rankList1: [],
        rankList2: [],
        defaultHeadImg: defaultContent.defaultHeadImg,
    },
    onLoad: function (options) {
        requestLock = false;
        tmpInterval = null;
        tmpInterval2 = null;
        baseMoney = 0;
        this.setData({
            userId: options.userId,
            openId: options.openId,
            name: options.name,
            headImg: options.headImg,
        });
    },
    onShow: function () {
        getGameState(this.data.userId).then((res) => {
            console.log(res);
            if (res.success) {
                if (res.data.status === '1') {
                    if (this.data.hbs.length === 0) {
                        this.getHbs();
                    }
                    clearInterval(tmpInterval2);
                    tmpInterval2 = null;
                    if (!tmpInterval) {
                        // 轮询更新红包列表
                        tmpInterval = setInterval(() => {
                            this.updateHbs(true);
                        }, 4000);
                    }
                } else if (res.data.status === '2') {
                    showWxToast('本轮红包墙已经结束');
                    timeoutTask(() => {
                        wx.navigateBack();
                    }, 1500);
                }
            }
        })
    },
    onHide: function () {
        //清除定时器
        clearInterval(tmpInterval);
        clearInterval(tmpInterval2);
        tmpInterval = null;
        tmpInterval2 = null;
    },
    onUnload: function () {
        //清除定时器
        clearInterval(tmpInterval);
        clearInterval(tmpInterval2);
        tmpInterval = null;
        tmpInterval2 = null;
    },
    enterGame: function () {
        getGameState(this.data.userId).then((res) => {
            console.log('***获取游戏状态***');
            console.log(res);
            if (res.success) {
                if (res.data.status === '0') {
                    showWxToast('请等待大屏开启游戏');
                } else if (res.data.status === '1') {
                    // 游戏进行中
                    console.log('***获取红包列表***');
                    this.getHbs();
                    clearInterval(tmpInterval);
                    tmpInterval = null;
                    if (!tmpInterval2) {
                        // 轮询更新红包列表
                        tmpInterval2 = setInterval(() => {
                            this.updateHbs(true);
                        }, 4000);
                    }
                } else if (res.data.status === '2') {
                    showWxToast('本轮开红包已经结束');
                    timeoutTask(() => {
                        wx.navigateBack();
                    }, 1500);
                } else {
                    showWxToast('请等待大屏开启游戏');
                }
            }
        }).catch((err) => {
            console.log(err);
        });
    },
    chooseHbs: function (e) {
        const index = this.findHbIndexByHbId(e.currentTarget.dataset.id);
        const hbs = this.data.hbs;
        if (hbs[index].isOpen) {
            showWxToast('这个红包已经被拆开啦！');
            return;
        }
        if (hbs[index].isBuyed) {
            showWxToast('这个红包已经被抢走啦！');
            return;
        }
        if (hbs[index].canBuy) {
            // 如果选中 取消选中
            if (hbs[index].isChoosed) {
                hbs[index].isChoosed = false;
                this.setData({
                    hbs,
                });
                this.updateGift();
                return;
            }
            // 最多3个红包 包括已经购买的
            const hasChoosedNum = this.getChoosedHbsNum(true);
            if (hasChoosedNum >= 3) {
                showWxToast('最多只能选择三个红包哦');
                return;
            }
            if (!hbs[index].isChoosed) {
                hbs[index].isChoosed = true;
                this.setData({
                    hbs,
                })
                this.updateGift();
            }
        }

    },
    // 获取红包列表
    getHbs: function () {
        getHbList(false).then((res) => {
            if (res.success) {
                console.log('***红包列表***');
                console.log(res);
                const tmpLen = res.data.list.length;
                const tmpHbs = [];
                let tmpNum = -1;
                let tmpState;
                let tmpIsOpen;
                let tmpIsBuyed;
                let tmpCanBuy;
                let tmpUserId;
                let tmpName;
                let tmpHeadImg;
                for (let i = 0; i < tmpLen; i += 1) {
                    if (i < 3) {
                        // +1
                        tmpNum = i + 1;
                    } else if (i < 12) {
                        // +2
                        tmpNum = i + 2;
                    } else if (i < 21) {
                        // +3
                        tmpNum = i + 3;
                    } else {
                        // +4
                        tmpNum = i + 4;
                    }
                    tmpIsOpen = false;
                    tmpIsBuyed = false;
                    tmpCanBuy = false;
                    tmpState = res.data.list[i].userId;
                    tmpUserId = '';
                    tmpName = '';
                    tmpHeadImg = '';
                    if (tmpState === '0') {
                        if (res.data.list[i].userInfo) {
                            // 未打开已购买
                            tmpIsBuyed = true;
                            tmpUserId = res.data.list[i].userInfo.USER_ID;
                            tmpName = res.data.list[i].userInfo.wx_name;
                            tmpHeadImg = res.data.list[i].userInfo.avator;
                        } else {
                            // 未打开未购买
                            tmpCanBuy = true;
                        }
                    } else if (tmpState === '100') {
                        // 红包已经在大屏被拆开
                        tmpIsOpen = true;
                        // 且被人购买
                        if (res.data.list[i].userInfo) {
                            tmpIsBuyed = true;
                            tmpUserId = res.data.list[i].userInfo.USER_ID;
                            tmpName = res.data.list[i].userInfo.wx_name;
                            tmpHeadImg = res.data.list[i].userInfo.avator;
                        }
                    } else {
                        // 红包已经被别人购买
                        tmpIsBuyed = true;
                        tmpUserId = res.data.list[i].userInfo.USER_ID;
                        tmpName = res.data.list[i].userInfo.wx_name;
                        tmpHeadImg = res.data.list[i].userInfo.avator;
                    }
                    tmpHbs.push({
                        id: res.data.list[i].eggId,
                        gold: res.data.list[i].money,
                        isOpen: tmpIsOpen,
                        isBuyed: tmpIsBuyed,
                        canBuy: tmpCanBuy,
                        isChoosed: false,
                        userId: tmpUserId,
                        name: tmpName,
                        headImg: tmpHeadImg,
                        num: tmpNum,
                    });
                }
                baseMoney = parseFloat(res.data.hbqMoney);
                this.setData({
                    hbs: tmpHbs,
                    gameStatus: 2,
                    sort: res.data.sort,
                });
                this.updateGift();
            } else {
                showWxToast('获取红包信息失败');
            }
        })
    },
    // 更新红包列表
    updateHbs: function (cancelLoading) {
        return new Promise((resolve, reject) => {
            getHbList(cancelLoading).then((res) => {
                if (res.success) {
                    console.log('***红包列表***');
                    console.log(res);
                    if (res.data.finished === '1') {
                        console.log('***结束递归***');
                        clearInterval(tmpInterval2);
                        clearInterval(tmpInterval);
                        tmpInterval2 = null;
                        tmpInterval = null;
                        this.handleGameEnd();
                        resolve();
                        return;
                    }
                    const tmpLen = res.data.list.length;
                    const tmpHbs = this.data.hbs;
                    let tmpNum = -1;
                    let tmpState;
                    let tmpIsOpen;
                    let tmpIsBuyed;
                    let tmpCanBuy;
                    let tmpUserId;
                    let tmpName;
                    let tmpHeadImg;
                    for (let i = 0; i < tmpLen; i += 1) {
                        if (i < 3) {
                            // +1
                            tmpNum = i + 1;
                        } else if (i < 12) {
                            // +2
                            tmpNum = i + 2;
                        } else if (i < 21) {
                            // +3
                            tmpNum = i + 3;
                        } else {
                            // +4
                            tmpNum = i + 4;
                        }
                        tmpIsOpen = false;
                        tmpIsBuyed = false;
                        tmpCanBuy = false;
                        tmpState = res.data.list[i].userId;
                        tmpUserId = '';
                        tmpName = '';
                        tmpHeadImg = '';
                        if (tmpState === '0') {
                            if (res.data.list[i].userInfo) {
                                // 未打开已购买
                                tmpIsBuyed = true;
                                tmpUserId = res.data.list[i].userInfo.USER_ID;
                                tmpName = res.data.list[i].userInfo.wx_name;
                                tmpHeadImg = res.data.list[i].userInfo.avator;
                            } else {
                                // 未打开未购买
                                tmpCanBuy = true;
                            }
                        } else if (tmpState === '100') {
                            tmpIsOpen = true;
                            if (res.data.list[i].userInfo) {
                                // 打开已购买
                                tmpIsBuyed = true;
                                tmpUserId = res.data.list[i].userInfo.USER_ID;
                                tmpName = res.data.list[i].userInfo.wx_name;
                                tmpHeadImg = res.data.list[i].userInfo.avator;
                            } else {
                                // 打开未购买
                                // 空操作
                            }
                        }
                        tmpHbs[i].isOpen = tmpIsOpen;
                        tmpHbs[i].isBuyed = tmpIsBuyed;
                        tmpHbs[i].canBuy = tmpCanBuy;
                        if (!tmpCanBuy && tmpHbs[i].isChoosed) {
                            // 选中的红包已经不可以购买了
                            tmpHbs[i].isChoosed = false;
                            this.updateGift();
                        }
                        tmpHbs[i].userId = tmpUserId;
                        tmpHbs[i].name = tmpName;
                        tmpHbs[i].headImg = tmpHeadImg;
                    }
                    this.setData({
                        hbs: tmpHbs,
                        sort: res.data.sort,
                    });
                    console.log(this.data.hbs);
                    resolve();
                } else {
                    reject();
                }
            })
        })
    },
    // 结束游戏获取排行榜
    handleGameEnd: function () {
        getHbRankList().then((res2) => {
            console.log('***排行榜****', res2);
            let tmpResultList = res2.data.list;
            let rankList1 = tmpResultList.slice(0, 3);
            let rankList2 = tmpResultList.slice(3, 10);
            // 游戏已经结束
            this.setData({
                gameStatus: 3,
                rankList1,
                rankList2,
            });
        }).catch((err) => {
            console.log(err);
        })
    },
    // 获取选择的红包数目时更新祝福列表
    updateGift: function () {
        const hasChoosedNum = this.getChoosedHbsNum(false);
        this.hbsMapGift(hasChoosedNum);
    },
    // 获取已经选择的红包id数组
    getChoosedHbIds: function () {
        const hbs = this.data.hbs;
        const len = hbs.length;
        const tmpChoosedHbIds = [];
        for (let i = 0; i < len; i += 1) {
            if (hbs[i].isChoosed) {
                tmpChoosedHbIds.push(hbs[i].id);
            }
        }
        return tmpChoosedHbIds;
    },
    // 获取选好的红包数目
    getChoosedHbsNum: function (isIncludeBuyed) {
        let tmpHbList = this.data.hbs;
        let tmpLen = tmpHbList.length;
        let tmpCount = 0;
        if (isIncludeBuyed) {
            for (let i = 0; i < tmpLen; i += 1) {
                if (tmpHbList[i].isChoosed || tmpHbList[i].userId === this.data.userId) {
                    tmpCount += 1;
                }
            }
        } else {
            for (let i = 0; i < tmpLen; i += 1) {
                if (tmpHbList[i].isChoosed) {
                    tmpCount += 1;
                }
            }
        }
        return tmpCount;
    },
    // 打开我的红包页面
    toMyHbs: function () {
        this.setData({
            myHbsVisible: true,
        });
    },
    // 打开红包购买页面
    toBuyHbs: function () {
        this.setData({
            myHbsVisible: false,
        });
    },
    // 红包选择个数映射礼物
    hbsMapGift: function (choosedNum) {
        const tmpMoney = baseMoney;
        giftList[0].price = tmpMoney.toFixed(2);
        giftList[1].price = (tmpMoney * 2).toFixed(2);
        giftList[2].price = (tmpMoney * 3).toFixed(2);
        if (choosedNum == 3) {
            //选了3个红包<--->大火箭
            this.setData({
                gift_show: giftList[2],
            })
        } else if (choosedNum == 2) {
            //选了2个红包<--->中火箭
            this.setData({
                gift_show: giftList[1],
            })
        } else {
            //选了1个红包或者还没有选红包<--->小火箭
            this.setData({
                gift_show: giftList[0],
            })
        }
    },
    // 通过hbId查找红包所在数组的索引
    findHbIndexByHbId: function (hbId) {
        let tmpIndex = -1;
        const tmpLen = this.data.hbs.length;
        for (let i = 0; i < tmpLen; i += 1) {
            if (this.data.hbs[i].id === hbId) {
                tmpIndex = i;
                break;
            }
        }
        return tmpIndex;
    },
    showLucky() {
        this.setData({
            luckyAni: 'showLuckyAni',
            isLuckyShow: true,
        });
        // 4s后消失
        timeoutTask(() => {
            this.setData({
                luckyAni: 'hideLuckyAni',
            });
            timeoutTask(() => {
                this.setData({
                    isLuckyShow: false,
                });
            }, 100);
        }, 4000)
    },
    // 买红包
    buy: function () {
        let choosed;
        this.updateHbs(false).then(() => {
            // 获取选中的红包
            choosed = this.getChoosedHbIds();
            console.log('***choosed***');
            console.log(choosed);
            if (choosed.length == 0) {
                showWxToast('请先选一个红包');
                return;
            }
            if (requestLock) {
                return;
            }
            requestLock = true;
            const chooseIdsStr = choosed.join(',');
            return this.robHb(chooseIdsStr, this.data.sort);
        }).then((res) => {
            console.log(res);
            if (!res) {
                return;
            }
            if (res.code === '200') {
                // 喵钻足正常抢红包
                if (res.resultList.length == 0) {
                    // 一个红包都没抢到
                    wx.showModal({
                        showCancel: false,
                        title: '温馨提示',
                        content: '很遗憾您选择的红包都被抢走了\r\n已退回至您的账户中',
                        confirmText: '确定',
                        success: () => {
                            this.updateHbs(false);
                        }
                    });
                } else {
                    // 至少抢到了一个
                    if (choosed.length > res.resultList.length) {
                        wx.showModal({
                            showCancel: false,
                            title: '温馨提示',
                            content: '恭喜您,成功抢到了' + res.resultList.length + '个红包！ \r\n 未抢到的红包，已退回至您的账户中',
                            confirmText: '确定',
                            success: () => {
                                this.updateHbs(false);
                            }
                        });
                    } else {
                        wx.showModal({
                            showCancel: false,
                            title: '温馨提示',
                            content: '恭喜您,成功抢到了' + res.resultList.length + '个红包!',
                            confirmText: '确定',
                            success: () => {
                                this.updateHbs(false);
                            }
                        });
                    }
                    console.log(res.resultList);
                    let tmpCode = '';
                    if (this.data.gift_show.id === 3) {
                        tmpCode = 7002;
                    } else if (this.data.gift_show.id === 2) {
                        tmpCode = 6002;
                    } else if (this.data.gift_show.id === 1) {
                        tmpCode = 5002;
                    }
                    let c = JSON.stringify({
                        code: tmpCode,
                        param: {
                            headImg: this.data.headImg,
                            nickname: this.data.name,
                            wish: wishList[getRandom(0, 4)],
                        }
                    });
                    // 发送广播
                    sendBroadCast({
                        c,
                    });
                    app.globalData.isH5NeedRefresh = true;
                }
                requestLock = false;
            } else if (res.code === '304') {
                // 喵钻不足
                if (res.NeedMoney) {
                    // 调起支付
                    return this.recharge(res.NeedMoney);
                } else {
                    showWxToast('购买失败');
                }
            } else if (res.code === '303') {
                // 用户信息异常
                showWxToast('用户信息异常');
                requestLock = false;
            } else if (res.code === '302') {
                // 一个人最多抢到3个红包
                showWxToast('一个人最多抢到3个红包');
                requestLock = false;
            } else if (res.code === '301') {
                // 不是最新的轮次
                showWxToast('不是最新的轮次');
                requestLock = false;
            } else {
                showWxToast('购买失败');
                requestLock = false;
            }
        }).catch((err) => {
            console.log(err);
            requestLock = false;
        })
    },
    // 抢红包
    robHb: function (pHbIdStr, pSort) {
        return new Promise((resolve, reject) => {
            showWxLoading('奋力争抢中...');
            buyHb({
                hbIds: pHbIdStr,
                sort: pSort,
            }).then((res) => {
                console.log(res);
                hideWxLoading();
                resolve(res);
            }).catch((err) => {
                console.log(err);
                reject(err);
                hideWxLoading();
                showWxToast('抢购失败');
            })
        });
    },
    // 支付
    recharge: function (money) {
        return new Promise((resolve, reject) => {
            hbqRecharge({
                userId: this.data.userId,
                openid: this.data.openId,
                money,
            }).then((res) => {
                console.log(res);
                if (res.status === 'success') {
                    wxPay(res).then((res2) => {
                        console.log(res2);
                        showWxToast('充值成功');
                        resolve(res2);
                        requestLock = false;
                        app.globalData.isH5NeedRefresh = true;
                        // 充值完成 等待后台加嗨币逻辑完成后 去买红包
                        timeoutTask(() => {
                            this.buy();
                        }, 500);
                    }).catch((err) => {
                        console.log(err);
                        showWxToast('充值失败');
                        requestLock = false;
                        reject(err);
                    })
                }
            }).catch((err) => {
                console.log(err);
                reject(err);
            })
        });
    },
    toAgreement: function () {
        wx.navigateTo({
            url: '/pages/agreement/agreement'
        });
    },
});